<template>
    <div class="main">
        <!-- 广告头部 -->
        <div>
            <el-space wrap :size="10">
                <el-select v-model="searchData.adStatus" placeholder="请选择广告状态" style="width: 10vw;" clearable>
                    <el-option :label="item.name" :value="item.value" v-for="item in adStatusMap" :key="item.value" />
                </el-select>
                <el-select v-model="searchData.adType" placeholder="请选择广告类型" style="width: 10vw;" clearable>
                    <el-option :label="item.name" :value="item.value" v-for="item in adTypeMap" :key="item.value" />
                </el-select>
                <el-button type="primary" :icon="Search" @click="handlerSearch">查找</el-button>
                <el-button type="primary" :icon="Plus" @click="handlerAddAd">添加</el-button>
            </el-space>
        </div>
        <div class="conten">
            <!-- 广告列表 -->
            <div>
                <el-table :data="tableData" style="width: 100%" border id="table">
                    <el-table-column label="广告ID" prop="id" align="center" />
                    <el-table-column label="广告标题" prop="title" align="center" />
                    <el-table-column label="广告图片" prop="imgUrl" align="center">
                        <template #default="scope">
                            <template v-if="adTypeMap.find(item => item.value == scope.row.type)?.picRequire">
                                <el-popover trigger="hover" placement="right" width="300px"
                                    :popper-style="'background-color:' + scope.row.color">
                                    <template #default>
                                        <div style="display: flex;justify-content: center;">
                                            <el-image style="width: 300px;" :src="scope.row.imgUrl" />
                                        </div>
                                    </template>
                                    <template #reference>
                                        <div>
                                            <el-image style="width: 100px;height: 50px;" :src="scope.row.imgUrl"
                                                fit="contain" />
                                        </div>
                                    </template>
                                </el-popover>
                            </template>
                            <template v-else>
                                <el-tag type="info">此类型无需图片</el-tag>
                            </template>
                        </template>
                    </el-table-column>
                    <el-table-column label="广告类型" prop="type" align="center">
                        <template #default="scope">
                            <template v-for="item in adTypeMap" :key="item.value">
                                <el-tag v-if="item.value == scope.row.type">{{ item.name }}</el-tag>
                            </template>
                        </template>
                    </el-table-column>
                    <el-table-column label="广告状态" prop="total" align="center">
                        <template #default="scope">
                            <el-tag :type="scope.row.status == 1 ? 'success' : 'danger'">{{ scope.row.status == 0 ?'冻结' : '激活'}}</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="关联类型" prop="unionType" align="center">
                        <template #default="scope">
                            <template v-for="item in adUinonTypeMap" :key="item.value">
                                <el-tag type="warning" v-if="item.value == scope.row.unionType">{{ item.name }}</el-tag>
                            </template>
                        </template>
                    </el-table-column>
                    <el-table-column label="关联值[ID]" prop="unionValue" align="center" />
                    <el-table-column label="创建时间" prop="gmtCreate" align="center">
                        <template #default="scope">
                            <template v-if="scope.row.gmtCreate">
                                {{ new Date(scope.row.gmtCreate).friendTime(1) }}
                            </template>
                            <template v-else>
                                <span>无</span>
                            </template>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" align="center" width="200">
                        <template #default="scope">
                            <el-button type='primary' @click="handleEdit(scope.row)">编辑</el-button>
                            <el-button type="danger" @click="handleDelete(scope.row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <!-- 创建和编辑对话框 -->
            <div>
                <el-dialog v-model="centerDialogVisible" :title='bool ? "创建" : "编辑"' align-center destroy-on-close>
                    <el-form ref="ruleFormRef" :model="ruleForm" status-icon :rules="rules" label-width="200px"
                        class="demo-ruleForm">
                        <el-form-item label="广告标题" prop="title" class="is-required">
                            <el-input v-model="ruleForm.title" autocomplete="off" />
                        </el-form-item>
                        <el-form-item label="广告类型" prop="type" class="is-required">
                            <el-select v-model="ruleForm.type" style="width: 10vw;" clearable @change="change">
                                <el-option :label="item.name" :value="item.value" v-for="item in adTypeMap"
                                    :key="item.value" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="广告图片" prop="imgUrl" class="is-required" id="upload" ref="upload"
                            v-if="adTypeMap.find(item => item.value == ruleForm.type)?.picRequire">
                            <el-upload class="avatar-uploader" :headers="headers" :show-file-list="false"
                                action="/upload/admin" :on-success="handleAvatarSuccess"
                                :before-upload="beforeAvatarUpload">
                                <img v-if="ruleForm.imgUrl" :src="ruleForm.imgUrl" class="avatar" />
                                <el-icon v-else class="avatar-uploader-icon">
                                    <Plus />
                                </el-icon>
                            </el-upload>
                        </el-form-item>
                        <el-form-item label="广告状态">
                            <el-switch v-model="ruleForm.status" class="ml-2" :active-value="1" :inactive-value="0"
                                style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" />
                        </el-form-item>
                        <el-form-item label="关联类型" prop="unionType" class="is-required">
                            <el-select v-model="ruleForm.unionType" placeholder="请选择" style="width: 10vw;" clearable
                                @change="ruleForm.unionValue = ''">
                                <el-option :label="item.name" :value="item.value" v-for="item in adUinonTypeMap"
                                    :key="item.value"
                                    :disabled="ruleForm.type == '' || adTypeMap.find(item => item.value == ruleForm.type)?.unionTypes.findIndex(items => items == item.value) == -1" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="商品" prop="unionValue" class="is-required" v-if="ruleForm.unionType == 1">
                            <el-cascader v-model="ruleForm.unionValue" :options="options" :props="props" clearable />
                        </el-form-item>
                        <el-form-item label="类目" prop="unionValue" class="is-required" v-if="ruleForm.unionType == 2">
                            <el-cascader v-model="ruleForm.unionValue" :options="option" :props="propst" clearable />
                        </el-form-item>
                        <el-form-item label="关键字" prop="unionValue" class="is-required" v-if="ruleForm.unionType == 3">
                            <el-input v-model="ruleForm.unionValue" autocomplete="off" />
                        </el-form-item>
                        <el-form-item label="功能" prop="unionValue" class="is-required" v-if="ruleForm.unionType == 4">
                            <el-select v-model="ruleForm.unionValue" placeholder="请选择" style="width: 10vw;" clearable>
                                <el-option :label="item.name" :value="item.value" v-for="item in functionPages"
                                    :key="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-form>
                    <template #footer>
                        <span class="dialog-footer">
                            <el-button @click="centerDialogVisible = false">取消</el-button>
                            <el-button type="primary" @click="submitForm(ruleFormRef)">确认</el-button>
                        </span>
                    </template>
                </el-dialog>
            </div>
        </div>
        <!-- 分页组件 -->
        <div>
            <Paging v-bind="pagingDatas" @page-change="pageChange"></Paging>
        </div>
        <el-backtop :right="100" :bottom="100" ref="main" target=".main"  :visibility-height="20" />
    </div>
</template>
<script lang="ts" setup>
import { ref, reactive, nextTick, watch } from 'vue'
import { ClassPagination, ClassAdPopup } from "#/index";
import Paging from "@/components/paging/Paging.vue";
import { post } from "@/utils/http";
import '@/utils/dataFriend'
import type { UploadProps } from 'element-plus'
import type { FormInstance } from 'element-plus'
import cookie from "js-cookie";
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus } from '@element-plus/icons-vue'
import { theColorFn } from "@/utils/theColor";

const searchData = reactive({
    adStatus: undefined,
    adType: undefined,
})
let upload = ref() //获取图片对象的引用的节点
const bool = ref(true) //判断是添加还是编辑
const options: TypeProductSku[] = reactive([]) //商品列表
const option: TypeCategory[] = reactive([]) //类目列表
const props = {
    emitPath: false,
    value: 'id',
    label: 'label',
    children: 'children'
}
const propst = {
    emitPath: false,
    checkStrictly: true,
    value: 'id',
    label: 'title',
    children: 'childrenList'
}
const ruleFormRef = ref<FormInstance>() 
let newSearchData = reactive({ ...searchData })
const centerDialogVisible = ref(false) //判断对话框是显示还是隐藏
const main = ref()  //滚动组件对象的引用
//添加弹出框绑定数据
let ruleForm = reactive(new ClassAdPopup)
let pagingDatas = reactive(new ClassPagination) //请求分页的数据
const tableData: TypeAdList[] = reactive([]) //广告列表
//关联类型
const adUinonTypeMap = reactive([
    { value: 1, name: '商品' },
    { value: 2, name: '类目' },
    { value: 3, name: '关键字' },
    { value: 4, name: '功能页面' },
])
//广告状态
const adStatusMap = reactive([
    { value: 0, name: '冻结' },
    { value: 1, name: '激活' },
])
//功能
const functionPages = reactive([
    { value: '/pages/product/groupshop', name: '团购列表' },
    { value: '/pages/coupon/list', name: '优惠券列表' },
])

//广告类型
const adTypeMap = reactive([
    { value: 1, unionTypes: [1, 2, 3, 4], picRequire: true, name: '轮播' },
    { value: 2, unionTypes: [2], picRequire: true, name: '分类精选' },
    { value: 3, unionTypes: [1, 2, 3, 4], picRequire: true, name: '横幅' },
    { value: 4, unionTypes: [1, 2, 3, 4], picRequire: true, name: '首页轮播下5按钮' },
    { value: 6, unionTypes: [1, 2, 3, 4], picRequire: false, name: '公告' },
    { value: 9, unionTypes: [1], picRequire: false, name: '商品推荐' },
])
//请求头
const headers = reactive({
    AdminToken: cookie.get('token')
})
//加载广告列表
const loadAdList = () => {
    let data = {
        _gp: 'admin.advert',
        _mt: 'list',
        pageNo: pagingDatas.page,
        limit: pagingDatas.limit,
        type: newSearchData.adType,
        status: newSearchData.adStatus
    }
    post(data).then(res => {
        console.log(res);
        let { errno, data, errmsg } = res
        if (200 == errno) {
            tableData.length = 0
            tableData.push(...data.items)
            pagingDatas.total = data.total
        } else {
            ElMessage.error(errmsg)
        }
    })
}
loadAdList()
//商品sku列表
const loadProductSku = () => {
    let data = {
        _gp: 'admin.product',
        _mt: 'getSpuBigTree'
    }
    if (options.length == 0) {
        post(data).then(res => {
            console.log(res);
            let { errno, errmsg, data } = res
            if (200 == errno) {
                options.length = 0
                options.push(...data)
            } else {
                ElMessage.error(errmsg)
            }
        })
    }
}
loadProductSku()
//类目列表
const lodeCategory = () => {
    let data = {
        _gp: 'admin.category',
        _mt: 'categoryTree'
    }
    if (option.length == 0) {
        post(data).then(res => {
            console.log(res);
            if (200 == res.errno) {
                option.length = 0
                option.push(...res.data)
            } else {
                ElMessage.error(res.errmsg)
            }
        })
    }
}
lodeCategory()


const newRuleForm = reactive({ ...ruleForm })

//非空验证
const validateTitle = (rule: any, value: any, callback: any) => {
    if (value === '' || value == undefined) {
        callback(new Error('请输入内容'))
    }
    callback()
}
//验证规则
const rules = reactive({
    title: [{ validator: validateTitle, trigger: 'blur' }],
    type: [{ validator: validateTitle, trigger: 'change' }],
    unionType: [{ validator: validateTitle, trigger: 'change' }],
    unionValue: [{ validator: validateTitle, trigger: ['blur', 'change'] }]
})

//添加
const handlerAddAd = () => {
    centerDialogVisible.value = true
    bool.value = true
    Object.assign(ruleForm, newRuleForm)
    ruleForm.imgUrl == '' ? 'https://www.baidu.com/img/flexible/logo/pc/result.png' : ruleForm.imgUrl
}
//编辑
const handleEdit = (row: TypeAdList) => {
    console.log(row);
    centerDialogVisible.value = true
    bool.value = false
    Object.assign(ruleForm, row)
    ruleForm.adId = row.id
    if (ruleForm.unionType < 3) {
        ruleForm.unionValue = parseInt(row.unionValue)
    }
    nextTick(() => {
        upload.value.$el.style.backgroundColor = ruleForm.color
    })
}
//添加和编辑确定
const submitForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {
            if (ruleForm.type == 6 || ruleForm.type == 9) {
                ruleForm.color = ''
                ruleForm.imgUrl = 'https://www.baidu.com/img/flexible/logo/pc/result.png'
            } else if (ruleForm.imgUrl == '') {
                ElMessage.error("图片不能为空")
                return
            }
            console.log(ruleForm.imgUrl);
            let data = {
                _gp: 'admin.advert',
                _mt: bool.value == true ? 'create' : 'edit',
                ...ruleForm
            }
            post(data).then(res => {
                console.log(res);
                let { errno, errmsg } = res
                if (200 == errno) {
                    centerDialogVisible.value = false
                    ElMessage.success(bool.value == true ? '添加成功' : '修改成功')
                    loadAdList()
                } else {
                    ElMessage.error(errmsg)
                }
            })

            console.log('submit!')
        } else {
            console.log('error submit!')
            return false
        }
    })
}
//图片上传后的函数
const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    console.log(response);
    if (200 == response.errno) {
        ruleForm.imgUrl = response.url
        theColorFn(ruleForm.imgUrl, (callback: string) => {
            ruleForm.color = callback
        })
    }
}
//规定上传图片的格式和大小
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/jpg' && rawFile.type !== 'image/png') {
        ElMessage.error('请选择jpeg、jpg、png格式图片上传')
        return false
    } else if (rawFile.size / 1024 / 1024 > 1) {
        ElMessage.error('图片大小不能超过1MB!')
        return false
    }
    return true
}
//更改广告类型清空下面的数据
const change = () => {
    ruleForm.unionType = ''
    if (bool.value == true) {
        ruleForm.color = ''
        ruleForm.imgUrl = ''
        nextTick(() => {
            upload.value.$el.style.backgroundColor = 'transparent'
        })
    }

}

//删除
const handleDelete = (row: TypeAdList) => {
    let data = {
        _gp: 'admin.advert',
        _mt: 'delete',
        type: row.type,
        adId: row.id
    }
    ElMessageBox.confirm(
        '请问是否删除',
        '消息提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
        }
    )
        .then(() => {
            post(data).then(res => {
                if (200 == res.errno) {
                    ElMessage.success('删除成功')
                    loadAdList()
                } else {
                    ElMessage.error(res.errmsg)
                }
            })

        })
        .catch(() => {
            ElMessage.info('取消操作')
        })
}

//查找
const handlerSearch = () => {
    Object.assign(newSearchData, searchData)
    pagingDatas.page = 1
    loadAdList()
}

//分页组件每次调用事件
function pageChange(e: TypePaGing) {
    pagingDatas.page = e._page
    pagingDatas.limit = e._limit
    loadAdList()
    nextTick(() => {
        main.value.$el.click?.()
    })
}
</script>
<style lang="less" scoped>
.main {
    >div {
        margin: 15px 0px;

        .el-input {
            width: 11vw;
        }
    }

    .conten {
        .el-dialog {
            .el-form {
                .el-form-item__content {
                    .el-input {
                        width: 20vw;
                    }
                }
            }
        }

        .avatar-uploader .avatar {
            width: 178px;
            height: 178px;
            display: block;
        }

        /deep/ .avatar-uploader .el-upload {
            border: 1px solid var(--el-border-color);
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
            transition: var(--el-transition-duration-fast);
        }

        .avatar-uploader .el-upload:hover {
            border-color: var(--el-color-primary);
        }

        .el-icon.avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 178px;
            height: 178px;
            text-align: center;
        }
    }
}
</style>